import request from '@/utils/request.js'
import store from '@/store/index.js'
const CHANNEL_KEY_TRAVEL = 'hm-channel-travel'
const CHANNEL_KET_VIP = 'hm-channel-vip'
export async function apiChannelList () {
  const key = store.state.user.token ? CHANNEL_KET_VIP : CHANNEL_KEY_TRAVEL
  const cacheChannels = localStorage.getItem(key)
  if (cacheChannels) {
    return { channels: JSON.parse(cacheChannels) }
  } else {
    const rst = await request({
      url: '/app/v1_0/user/channels',
      method: 'get'
    })
    localStorage.setItem(key, JSON.stringify(rst.channels))
    return rst
  }
}

export function apiChannelAll () {
  return request({
    url: '/app/v1_0/channels',
    method: 'get'
  })
}

export async function apiChannelAdd (channel) {
  const key = store.state.user.token ? CHANNEL_KET_VIP : CHANNEL_KEY_TRAVEL
  const cacheChannels = JSON.parse(localStorage.getItem(key))
  cacheChannels.push(channel)
  localStorage.setItem(key, JSON.stringify(cacheChannels))
  return null
}

export async function apiChannelDel (channel) {
  const key = store.state.user.token ? CHANNEL_KET_VIP : CHANNEL_KEY_TRAVEL
  const cacheChannels = JSON.parse(localStorage.getItem(key))
  const tmpChannels = cacheChannels.filter(item => {
    return channel.id !== item.id
  })
  localStorage.setItem(key, JSON.stringify(tmpChannels))
  return null
}
